﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace PDX
{
    /// <summary>
    /// A default <see cref="IValidationAdapter"/>.
    /// Supports IDataErroInfo.
    /// </summary>
    public class DefaultValidationAdapter : IValidationAdapter
    {
        /// <summary>
        /// Gets the metadata.
        /// </summary>
        public ViewmodelMetadata Metadata { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultValidationAdapter"/> class.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        public DefaultValidationAdapter(ViewmodelMetadata metadata)
        {
            this.Metadata = metadata;
            Metadata.Notifier.PropertyChanged += notifier_PropertyChanged;
        }

        /// <summary>
        /// Called when the <see cref="NotificationManager"/> raises PropertyChanged.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
        protected virtual void notifier_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var temp = ValidationChanged;
            if (temp != null)
            {
                temp(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// Gets the error message, if any.
        /// </summary>
        /// <param name="propModel">The prop model.</param>
        /// <returns></returns>
        public virtual string GetMessage(IPropertyModel propModel)
        {
            var iData = propModel.Resolution.ResolvedDC as IDataErrorInfo;
            if (iData != null)
            {
                return iData[propModel.Resolution.Property.Name];
            }

            return string.Empty;
        }

        /// <summary>
        /// Occurs when the validation result has changed.
        /// </summary>
        public event EventHandler<EventArgs> ValidationChanged;
    }
}
